package com.kofan.shelter.commons.util.utils;

import com.kofan.shelter.api.bean.Token;
import com.kofan.shelter.api.constants.TokenConstants;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Base64;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Component
public class TokenUtil {
    @Resource
    private RedisTemplate<String, String> redisTemplate;

    public String createToken(Token value) {
		String encode = value.getUserId();
		String template = redisTemplate.opsForValue().get(TokenConstants.REDIS_TOKEN + encode);
		if (StringUtils.isEmpty(template)) {
			String uuidV = UUID.randomUUID().toString().replaceAll("-", "");
            //token 存两个 一个是key uuId 另一个根据userId 查token
			redisTemplate.opsForValue().set(uuidV,encode, 24, TimeUnit.HOURS);
			redisTemplate.opsForValue().set(TokenConstants.REDIS_TOKEN + encode,uuidV, 24, TimeUnit.HOURS);
			return uuidV;
		} else {
            //续期
            redisTemplate.opsForValue().set(TokenConstants.REDIS_TOKEN + encode,template, 24, TimeUnit.HOURS);
			redisTemplate.opsForValue().set(template,encode, 24, TimeUnit.HOURS);
			return template;
		}
    }

    public String getTokenValue(String key) {
        String template = redisTemplate.opsForValue().get(key);
        return template;
    }

    public void delToken(String userId) {
        String s = redisTemplate.opsForValue().get(TokenConstants.REDIS_TOKEN + userId);
        redisTemplate.delete(s);
        redisTemplate.delete(TokenConstants.REDIS_TOKEN + userId);
    }
}
